<template>
  <view class="main">
    <view class="title-box">"{{ titleName }}"的对话</view>
    <image :src="picture" mode="widthFix" class="banner-img"></image>
    <view class="textBox" v-if="activeTap == 0">
      <text
        class="text"
        v-for="(item, index) in asList"
        :key="index"
        :class="
          currentTime > item.startSeconds && currentTime < item.endSeconds
            ? 'activeText'
            : ''
        "
        >{{ item.text }}</text
      >
    </view>
    <view v-if="activeTap == 1">
      <view class="textBox">
        <view v-for="(item, index) in readList" :key="index">
          <text class="text" :class="readLine == index ? 'activeText' : ''">{{
            item.text
          }}</text>
          <view class="result-wrap" v-if="item.isShowResult">
            <view class="comment-box">
              <view class="result-bar"> {{ item.result }} </view>
              <view class="comment-bar">
                <view v-if="!item.isShowComment">分值计算中...</view>
                <TnRate
                  v-if="item.isShowComment"
                  v-model="item.rateValue"
                  active-color="#FAC909"
                  :min="0"
                  :max="5"
                  allow-half
                  :readonly="true"
                  style="float: right; margin-top: 18rpx"
                />
              </view>
            </view>
            <image
              src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/test1.png"
              mode="widthFix"
            />
          </view>
          <TnCircleProgress
            :percent="progressPercent"
            :duration="duration"
            v-if="readLine == index"
            :show-percent="true"
          >
            <text>{{
              ifReading ? '请开始朗读' : '评分中 '
            }}</text></TnCircleProgress
          >
        </view>
      </view>
      <!-- <TnPopup v-model="showtipPopup">
        <view class="tn-p-lg"> 请在规定时间内朗读下面的句子 </view>
      </TnPopup> -->
    </view>
    <view class="bottom_box">
      <view class="imgBox">
        <button open-type="share">
          <TnIcon name="share-square" size="50rpx" />
        </button>
        <TnIcon
          name="praise"
          size="50rpx"
          :color="ifZanStatus == 1 ? '#4b49e8' : ''"
          @tap.stop="onZanIconClick"
          :custom-style="{ margin: '0 20rpx' }"
        />
        <TnIcon
          name="tread"
          size="50rpx"
          @tap.stop="onCaiIconClick"
          :color="ifZanStatus == 2 ? '#4b49e8' : ''"
        />
      </view>
      <view class="wrap">
        <view class="btn-box" @click="toListing">
          <TnIcon
            name="sound-fill"
            size="80rpx"
            :color="activeTap == 0 ? '#4b49e8' : ''"
          />
          <view class="btn-item">AI朗读</view>
        </view>
        <view class="btn-box" style="margin-bottom: 40rpx" @click="toReading">
          <TnIcon
            name="voice-fill"
            size="80rpx"
            :color="activeTap == 1 ? '#4b49e8' : ''"
          />
          <view class="btn-item">智能跟读</view>
        </view>
        <view class="btn-box" @click="toChangeNew">
          <span :class="isAnimation ? 'refish' : ''">
            <!-- <TnIcon
            name="transfer-circle-fill"
            size="80rpx"
            :color="activeTap == 2 ? '#4b49e8' : ''"
        /> -->
            <TnIcon
              name="refresh"
              size="80rpx"
              :color="activeTap == 2 ? '#4b49e8' : ''"
            />
          </span>
          <view class="btn-item">AI换一批</view>
        </view>
      </view>
    </view></view
  >
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import { getSceneDetailById, toDown, toUp } from '@/services/api'
import { Base64 } from 'js-base64'
import { useWebsocket } from '@/hooks'
import srtParser2 from 'srt-parser-2'
import TnCircleProgress from '@tuniao/tnui-vue3-uniapp/components/circle-progress/src/circle-progress.vue'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'
import string from '@tuniao/tnui-vue3-uniapp/libs/async-validator/validator/string'
var plugin = requirePlugin('WechatSI')
let manager = plugin.getRecordRecognitionManager()
const {
  connectWebSocketComment,
  connectWebSocket,
  APPID,
  toBase64,
  handlePlayVideo,
  textTranslate,
  webSocketSendComment,
  webSocketSend,
  base64toJson,
  handleClickVideo,
  webSocketSendMp3,
  handleCloseVideo,
  splitText,
  closeWebSocket,
} = useWebsocket()
const innerAudioContext = uni.createInnerAudioContext()
const answer = ref('')
const audioSrc = ref('')
const titleName = ref('')
const answerList = ref([] as any)
const activeWord = ref()
const answering = ref(false)
const currentTime = ref(0)
const picture = ref('')
const asList = ref([] as any)
const audio = ref('')
const playing = ref(false)
let music = uni.createInnerAudioContext()
let promptSound = uni.createInnerAudioContext() //提示音
const overMp3 =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/over.mp3'
const niceMp3 =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/nice.mp3'
const excellent =
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/mp3/excellent.mp3'
// music.src =
//   'https://api.chongli.maiyajia.com/uploads/01_hello_lesson1_4980ad0a58.MP3'
const activeTap = ref(0) //0为AI朗读，1为智能跟读
const readLine = ref(-1) //当前需要朗读的第几行
// const showtipPopup = ref(true)
const progressPercent = ref(100) //进度条百分比
const ifReading = ref(false) //是否朗读中
const duration = ref(0) //当前句子的时长
const currentItem = ref({} as any) //当前朗读的句子
const tempFilePath = ref() //录音文件
const readList = ref([] as any) //跟读句子列表
const isAnimation = ref(false)
// 获取录音
const recorderManager = uni.getRecorderManager()
const ids = ref([]) //读过的文章id
const styleId = ref('')
const ifZanStatus = ref(0) //0初始值，1赞,2踩
const asDetail = ref({} as any) //文章详情
const changeTap = (index: number) => {
  if (activeTap.value == 0 && index == 0) {
    console.log('开始播放')
    onPlayIconClick()
  } else {
    music.stop()
    playing.value = false
  }
  activeTap.value = index
}
const toListing = () => {
  if (activeTap.value == 0) {
    console.log('开始播放和暂停')
    onPlayIconClick()
  } else {
    activeTap.value = 0
  }
}
const toReading = () => {
  music.stop()
  playing.value = false
  readList.value = JSON.parse(JSON.stringify(asList.value))
  console.log('智能跟读', readList.value)
  //刷新
  refresh()
  activeTap.value = 1
}

watch(
  () => activeTap.value,
  (newProps) => {
    console.log(newProps)
    if (newProps == 1) {
      // 智能跟读模块的初始化
      uni.showModal({
        title: '提示',
        content: '请在规定时间内朗读下面的句子',
        success: function (res) {
          if (res.confirm) {
            console.log('立即朗读')
            readLine.value = 0
            readSentence()
          } else if (res.cancel) {
            console.log('先不朗读')
          }
        },
      })
      // showtipPopup.value = true
    }
  }
)
//朗读倒计时
const readSentence = () => {
  if (readLine.value > readList.value.length - 1) {
    // 朗读结束刷新
    refresh()
    return false
  } else {
    console.log('33333', readList.value)
    //当前需要朗读的第几行
    ifReading.value = true
    currentItem.value = readList.value[readLine.value]
    duration.value =
      (currentItem.value.endSeconds - currentItem.value.startSeconds) * 1000 +
      3000
    //打开websoket
    startRecord()
    setTimeout(() => {
      endRecord()
    }, duration.value)
  }
}

// 朗读开始录制
const startRecord = () => {
  try {
    console.log(
      'sdhcdbcdjncdkmckl/dmfm l.mk/md;.',
      readList.value[readLine.value]
    )
    connectWebSocket().then((res) => {
      if (res != '') {
        console.log(
          '识别到文字成功返回识别到文字成功返回识别到文字成功返回',
          res
        )
        readList.value[readLine.value].result = res
        readList.value[readLine.value].isShowResult = true
      } else {
        console.log('3333', res)
        readList.value[readLine.value].isShowResult = false
        uni.showToast({
          title: '未识别到文字',
          icon: 'none',
        })
      }
    })
    // 评分
    connectWebSocketComment(readList.value[readLine.value].text)
      .then((res) => {
        console.log('4444', res)
        readList.value[readLine.value].isShowComment = true
        readList.value[readLine.value].rateValue = Number(res.total_score)
        if (!readList.value[readLine.value].hasOwnProperty('repeatNum')) {
          readList.value[readLine.value].repeatNum = 0
        }
        console.log('成功评分结果', readList.value[readLine.value])
        //打分成功且分数大于三分则继续朗读下一句
        if (
          readList.value[readLine.value].rateValue < 3 &&
          readList.value[readLine.value].repeatNum < 1
        ) {
          uni.showToast({
            title: '不合格再读一遍吧',
            icon: 'none',
            duration: 2000,
          })
          playSound(readList.value[readLine.value].rateValue).then(() => {
            console.log('444播放结束')
            let currentIndex = readLine.value
            readLine.value = -1
            setTimeout(() => {
              console.log('777播放结束')
              readLine.value = currentIndex
              readList.value[readLine.value].repeatNum += 1
              readSentence()
              console.log('888播放结束')
            }, 2000)
          })
          // //播放提示音
          // playSound(readList.value[readLine.value].rateValue)
          // //监听提示音播放结束
          // promptSound.onEnded(() => {
          //   console.log('333播放结束')
          //   promptSound.stop()
          //   promptSound.destroy()
          //   console.log('444播放结束')
          //   let currentIndex = readLine.value
          //   readLine.value = -1
          //   setTimeout(() => {
          //     console.log('777播放结束')
          //     readLine.value = currentIndex
          //     readList.value[readLine.value].repeatNum += 1
          //     readSentence()
          //     console.log('888播放结束')
          //   }, 2000)
          // })
        } else {
          // //播放提示音
          // playSound(readList.value[readLine.value].rateValue)
          // //监听提示音播放结束
          // promptSound.onEnded(() => {
          //   console.log('555播放结束')
          //   promptSound.stop()
          //   promptSound.destroy()
          //   readLine.value += 1
          //   readSentence()
          //   console.log('666播放结束')
          // })
          if (
            readList.value[readLine.value].repeatNum >= 1 &&
            readList.value[readLine.value].rateValue < 3
          ) {
            readLine.value += 1
            readSentence()
          } else {
            playSound(readList.value[readLine.value].rateValue).then(() => {
              readLine.value += 1
              readSentence()
              console.log('666播放结束')
            })
          }
        }
      })
      .catch((err) => {
        console.log('成功失败结果', err)
        readList.value[readLine.value].isShowComment = false
        readList.value[readLine.value].rateValue = 0
        console.log(readList.value[readLine.value])
        uni.showToast({
          title: '识别失败请再读一遍',
          icon: 'none',
          duration: 2000,
        })
        //播放提示音
        // playSound(readList.value[readLine.value].rateValue)
        // //监听提示音播放结束
        // promptSound.onEnded(() => {
        //   console.log('333播放结束')
        //   promptSound.stop()
        //   promptSound.destroy()
        //   let currentIndex = readLine.value
        //   readLine.value = -1
        //   setTimeout(() => {
        //     readLine.value = currentIndex
        //     readSentence()
        //   }, 2000)
        // })
        playSound(readList.value[readLine.value].rateValue).then(() => {
          let currentIndex = readLine.value
          readLine.value = -1
          setTimeout(() => {
            readLine.value = currentIndex
            readSentence()
          }, 2000)
        })
      })
    recorderManager.start({
      duration: 30000, // 600000（10 分钟）,默认值 60000（1 分钟）
      numberOfChannels: 1, // 录音通道数，有效值 1/2
      frameSize: 1,
      format: 'pcm', // 音频格式
      sampleRate: 16000, // 采样率
    })
    console.log('7777')
  } catch (e) {
    console.log('错误了', e)
  }

  // state.list[currentIndex.value].isShowResult = true
  // 常规
}

// 朗读停止
const endRecord = () => {
  console.log(
    '朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束朗读结束'
  )
  // state.currentItem = item
  // currentIndex.value = index
  recorderManager.stop()
  ifReading.value = false
  // animation.value = false
}
const startWatch = () => {
  var lastFrame = [] as any
  recorderManager.onStop(function (res) {
    console.log('6666', lastFrame)
    // 监听最后一帧
    // 基础
    webSocketSend(lastFrame, true).then((res) => {
      if (res == 'success') {
      }
    })
    webSocketSendComment(
      lastFrame,
      readList.value[readLine.value].text,
      true
    ).then((res) => {
      if (res == 'success') {
      }
    })

    console.log('8888', res)
    let tempFile = res.tempFilePath //音频文件地址
    tempFilePath.value = tempFile
    // #ifdef MP-WEIXIN
    const fs = uni.getFileSystemManager()
    // 评分
    fs.readFile({
      //读取文件并转为ArrayBuffer
      filePath: tempFile,
      success(res) {},
    })
    // #endif
  })
  recorderManager.onFrameRecorded(function (res) {
    console.log('9999', res)
    const { frameBuffer, isLastFrame } = res
    lastFrame = frameBuffer
    let newFrameBuffer = Array.from(new Uint8Array(frameBuffer))
    // 基础
    webSocketSend(frameBuffer, isLastFrame).then((res) => {
      if (res == 'success') {
      }
    })
    // 评分
    webSocketSendComment(
      frameBuffer,
      readList.value[readLine.value].text,
      isLastFrame
    ).then((res) => {
      if (res == 'success') {
      }
    })
  })
}
//刷新智能跟读
const refresh = () => {
  readLine.value = -1
  ifReading.value = false
  duration.value = 0
  currentItem.value = {}
}
//换一批
const toChangeNew = () => {
  isAnimation.value = true
  getData()
}

const onPlayIconClick = () => {
  if (playing.value) {
    music.pause()
    playing.value = false
  } else {
    music.play() //执行播放
    music.onPlay(() => {
      console.log('开始播放')
      playing.value = true
    })
    music.onTimeUpdate(() => {
      currentTime.value = music.currentTime
      console.log(currentTime.value)
    })
    music.onEnded(() => {
      //播放结束
      music.stop()
      playing.value = false
      console.log('播放结束')
    })
  }
}

const str = ref('')
var parser = new srtParser2()

onLoad((options) => {
  console.log(options)
  // var srt_string = parser.toSrt(srt_array)
  // console.log(srt_string)
  // asList.value.forEach((item) => {
  //   item.startTime = setTime(item.startTime)
  //   item.endTime = setTime(item.endTime)
  // })
  const { id, name, answerZh } = options
  styleId.value = id
  if (styleId.value) {
    getData()
  }
  if (name) {
    titleName.value = name
  }
  if (answerZh) {
    onTranslate(answerZh)
  }
  startWatch()
})

onHide(() => {
  music.stop()
  closeWebSocket()
})
onUnload(() => {
  readList.value = []
  console.log('onUnload')
  music.stop()
  closeWebSocket()
})
const animation = () => {
  console.log('animation结束')
  isAnimation.value = false
}
//将'00:01:60,888'格式时间转化为秒
const setTime = (time) => {
  let aTime = time.split(',')[0]
  let sTime = '.' + time.split(',')[1]
  let s = aTime.split(':')[0]
  let f = aTime.split(':')[1]
  let m = aTime.split(':')[2]
  let allTime = Number(s * 3600 + f * 60 + Number(m) + sTime)
  return allTime
}
const getData = () => {
  let params = { ids: ids.value }
  getSceneDetailById(styleId.value, params).then((res) => {
    const { code, data } = res
    if (code === 0) {
      if (data.id !== 0) {
        console.log('data', data)
        // // answer.value = Base64.decode(data.content) //Base64解密
        // answer.value = data.content
        // // answer.value.replace(/[\n\r]/g, '<br>')
        // answerList.value = answer.value.split(/\n/)
        asDetail.value = data
        str.value = data.subtitles
        asList.value = parser.fromSrt(str.value)
        ids.value.push(data.id)
        console.log('uuuuu', asList.value)
        music.src = data.audio
        audio.value = data.audio
        picture.value = data.picture
        ifZanStatus.value = data.like
        readList.value = JSON.parse(JSON.stringify(asList.value))
      } else {
        uni.showToast({
          title: '暂时没有更多咯!',
          icon: 'none',
          duration: 2000,
        })
      }
    }
    setTimeout(() => {
      isAnimation.value = false
    }, 2000)
  })
}

//点赞
const onZanIconClick = async () => {
  const res = await toUp(asDetail.value.id)
  if (res.code === 0) {
    if (res.status === 1) {
      ifZanStatus.value = 1
      uni.showToast({
        title: '已赞',
        duration: 2000,
      })
    } else if (res.status === 0) {
      ifZanStatus.value = 0
    }
  } else {
    uni.showToast({
      title: res.msg,
      duration: 2000,
    })
  }
}
// 点踩
const onCaiIconClick = async () => {
  const res = await toDown(asDetail.value.id)
  if (res.code === 0) {
    if (res.status === 2) {
      ifZanStatus.value = 2
      uni.showToast({
        title: '已踩',
        duration: 2000,
      })
    } else if (res.status === 0) {
      ifZanStatus.value = 0
    }
  } else {
    uni.showToast({
      title: res.msg,
      duration: 2000,
    })
  }
}
//提示音播放
const playSound = (score) => {
  return new Promise((resolve, reject) => {
    let sound =
      score < 3
        ? overMp3
        : 3 <= score && score < 4
          ? niceMp3
          : score >= 4
            ? excellent
            : ''
    promptSound.src = sound
    promptSound.play() //执行播放
    console.log('开始播放')
    promptSound.onEnded(() => {
      promptSound.stop()
      console.log('播放结束')
      resolve(true)
    })
    // promptSound.onPlay(() => {
    //   console.log('开始播放')
    // })
    promptSound.onError((res) => {
      console.log(res.errMsg)
    })
  })
}

const jumpBreakAnswerPage = () => {
  let encoded = Base64.btoa(
    unescape(encodeURIComponent(JSON.stringify(asList.value)))
  )
  tnNavPage(
    `/home-page/agent/break-answer?answerEn=${encoded}&source=2&audio=${audio.value}`
  )
}

//中文翻译成英文
const onTranslate = (answerZh) => {
  plugin.translate({
    lfrom: 'zh_CN',
    lto: 'en_US',
    content: answerZh,
    success: function (res) {
      if (res.retcode == 0) {
        answer.value = res.result
        outputText(answer.value)
      } else {
        console.warn('翻译失败', res)
      }
    },
    fail: function (res) {
      console.log('网络失败', res)
    },
  })
}

//流式输出文字
const outputText = (text) => {
  var index = 0
  const streamOutput = () => {
    if (index < text.length) {
      var currentText = text.substring(0, index + 1)
      answer.value = currentText
      index++
    } else {
      clearInterval(timer)
    }
  }
  let timer = setInterval(streamOutput, 20)
}

//英文转语音
// const textToSpeech = () => {
//   return new Promise((resolve, reject) => {
//     plugin.textToSpeech({
//       lang: 'en_US',
//       tts: true,
//       content:
//         answer.value.length < 900 ? answer.value : answer.value.slice(0, 900),
//       success: function (res) {
//         console.log('succ tts', res.filename)
//         audioSrc.value = res.filename
//         resolve()
//       },
//       fail: function (res) {
//         console.log('fail tts', res)
//       },
//     })
//   })
// }

const stopAudio = () => {
  innerAudioContext.stop()
}

//讯飞的语音播放接口
// const onPlayIconClick = async () => {
//   // Chinese中文 | English英文
//   answerList.value = answer.value.split(/\n/)
//   console.log(answerList.value)
//   playAudio(0)
// }
//利用递归函数去遍历每一句话的播放
// const playAudio = async (sum: number) => {
//   try {
//     let answerIndex = sum
//     if (answerIndex < answerList.value.length) {
//       // 发送消息获取音频并处理
//       const res = await webSocketSendMp3(
//         answerList.value[answerIndex],
//         'English'
//       )
//       let audioDataArray = [] as any
//       res.forEach((item, index) => {
//         const arrayBuffer = wx.base64ToArrayBuffer(item)
//         const newBuffer = new Uint8Array(arrayBuffer)
//         audioDataArray.push(...newBuffer)
//       })
//       const uint8Array = new Uint8Array(audioDataArray)
//       const audioUrl = wx.createBufferURL(uint8Array.buffer)

//       // 播放音频并处理播放状态,播放该句子就会高亮，该句子的索引
//       activeWord.value = answerIndex
//       answering.value = true
//       await handlePlayVideo(audioUrl)

//       // 继续播放下一句
//       await playAudio(answerIndex + 1)
//     } else {
//       answering.value = false
//     }
//   } catch (error) {
//     console.error('播放音频时出错：', error)
//     // 可以添加错误处理逻辑，比如重试播放或提醒用户
//   }
// }
const onCopyIconClick = () => {
  uni.setClipboardData({
    data: answer.value,
    success: function () {},
  })
}
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  min-height: 100%;
  padding: 32rpx;
  .banner-img {
    width: 100%;
    margin-bottom: 24rpx;
  }
  .textBox {
    .text {
      width: 100%;
      display: block;
      line-height: 44rpx;
      font-size: 28rpx;
      color: #191919;
      border-radius: 22rpx;
      margin-bottom: 20rpx;
      background-color: #ecf5f4;
      padding: 10rpx;
    }
    .activeText {
      color: #4b49e8;
      font-size: 30rpx;
      font-weight: bold;
    }
    .result-wrap {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 100%;
      .comment-box {
        max-width: 500rpx;
        background: #fff;
        display: flex;
        align-items: flex-end;
        padding: 20rpx;
        border-radius: 40rpx;
        flex-direction: column;
      }
      image {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
      }
    }
  }
  .bottom_box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    .imgBox {
      display: flex;
      justify-content: flex-end;
      padding-right: 38rpx;
      button {
        margin: 0;
        background: none;
        padding: 0;
      }
    }

    .wrap {
      display: flex;
      justify-content: space-between;
      width: 100%;
      padding: 0 30rpx;

      .btn-box {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        width: 200rpx;
        .refish {
          transition: 1s;
          transform: rotate(360deg);
        }
      }
    }
  }
}
</style>
